package com.jingwu.example.config.filter;

import cn.hutool.core.util.RandomUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import graphql.ExecutionResultImpl;
import graphql.servlet.GenericGraphQLError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jingwu
 * @since 2021/2/5
 */
@Component
public class AuthFilter extends OncePerRequestFilter {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (doAuth(request)) {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            ExecutionResultImpl build = ExecutionResultImpl.newExecutionResult()
                    .addError(new GenericGraphQLError("认证失败"))
                    .data(null)
                    .build();
            response.getWriter().write(objectMapper.writeValueAsString(build.toSpecification()));
            return;
        }

        filterChain.doFilter(request, response);
    }

    private boolean doAuth(HttpServletRequest request) {
        // mock auth result
        return RandomUtil.randomBoolean();
    }
}
